package com.itcast.service.impl;

import com.alibaba.fastjson.JSON;
import com.itcast.pojo.GoodInfo;
import com.itcast.service.IGoodsService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author feng js
 */
@Service
@Slf4j
public class CoodServiceImpl implements IGoodsService {

    @Autowired
    RestHighLevelClient restHighLevelClient;

    @Override
    public List<GoodInfo> searchByTitle(String keyword, Integer page, Integer pagesize) throws IOException {
        List<GoodInfo> list = new ArrayList<>();
        SearchRequest request = new SearchRequest("goods");
        SearchSourceBuilder builder = new SearchSourceBuilder();
        builder.query(QueryBuilders.matchQuery("title",keyword));
        int from = (page-1)*pagesize;
        builder.from(from);
        builder.size(pagesize);
        SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
        SearchHits hits = response.getHits();
        SearchHit[] searchHits = hits.getHits();
        for (SearchHit searchHit : searchHits) {
            String sourceAsString = searchHit.getSourceAsString();
            GoodInfo goodInfo = JSON.parseObject(sourceAsString, GoodInfo.class);
            list.add(goodInfo);
        }
        log.info(list.toString());
        return list;
    }
}
